<template>
  <div>
    <el-row type="flex" justify="center">
      <el-col :span="12">
        <el-card>
          <template #header>
            <el-row type="flex" justify="end" :gutter="20">
              <el-col :span="2">
                <el-button type="primary" icon="el-icon-plus" @click="showAddDialog" />
              </el-col>
              <el-col :span="2">
                <el-button type="primary" icon="el-icon-edit" @click="showEditDialog" :disabled="!onlyOneSelected"/>
              </el-col>
              <el-col :span="2">
                <el-button type="danger" icon="el-icon-delete" @click="showDelDialog" :disabled="noOneSelected"/>
              </el-col>
            </el-row>
          </template>
          <el-table
              :data="categories"
              max-height="550"
              stripe
              :default-sort = "{prop: 'id', order: 'ascending'}"
              @selection-change="handleSelection">
            <el-table-column
                type="selection"
                width="55"/>
            <el-table-column label="ID" prop="id" align="center" sortable />
            <el-table-column label="类别" prop="name" align="center" sortable/>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

<!--  添加与修改对话框  -->
    <el-dialog title="添加类别" width="40%" :visible.sync="dialogAdd">
      <el-input v-model="form.name" placeholder="请输入类别名称" />

      <template #footer>
        <el-row type="flex" justify="end" :gutter="20">
          <el-col :span="3">
            <el-button @click="cancel">取消</el-button>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="add">确定</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>

    <el-dialog title="修改类别" width="40%" :visible.sync="dialogEdit">
      <el-input v-model="form.name" placeholder="请输入新的类别名称" />

      <template #footer>
        <el-row type="flex" justify="end" :gutter="20">
          <el-col :span="3">
            <el-button @click="cancel">取消</el-button>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="edit">确定</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>

<!--  删除对话框  -->
    <el-dialog
        title="删除类别"
        :visible.sync="dialogDel"
        width="30%">
      <span>您确定要删除选中的{{ this.selected.length }}个类别吗？</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancel">取消</el-button>
    <el-button type="danger" @click="del">确定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "ManageCategoriesView",
  data() {
    return {
      categories: [],
      selected : [],
      form: {
        id: null,
        name: null
      },
      dialogAdd: false,
      dialogEdit: false,
      dialogDel: false
    }
  },
  methods: {
    errorHandler(e) {
      if (e.response) {
        this.$message({
          message: `未知的服务器错误 代码${e.response.status}`,
          type: "error"
        });
      } else {
        this.$message({
          message: `未知的错误`,
          type: "error"
        });
      }
      loading.close();
    },
    fetchCategories() {
      axios.get("/api/book/fetchCategories")
          .then(val => {
            this.categories = val.data;
          })
          .catch(this.errorHandler);
    },
    showAddDialog() {
      this.dialogAdd = true;
    },
    showEditDialog() {
      this.form.id = this.selected[0].id;
      this.dialogEdit = true;
    },
    showDelDialog() {
      this.dialogDel = true;
    },
    add() {
      const {name} = this.form;
      this.addCategory(name)
          .then(this.fetchCategories)
          .catch(this.errorHandler)
          .finally(() => {
            this.dialogAdd = false;
            this.form.name = null;
          });
    },
    del() {
      let promises = this.selected.map(value => this.delCategory(value.id));
      Promise.all(promises)
          .then(this.fetchCategories)
          .catch(this.errorHandler)
          .finally(() => {
            this.dialogDel = false;
          })
    },
    edit() {
      const {id, name} = this.form;
      this.editCategory(id, name)
          .then(this.fetchCategories)
          .catch(this.errorHandler)
          .finally(() => {
            this.dialogEdit = false;
            this.form.id = null;
            this.form.name = null;
          });
    },
    cancel() {
      this.dialogAdd = this.dialogEdit = this.dialogDel = false;
      this.form.id = null;
      this.form.name = null;
    },
    async addCategory(name) {
      await axios.post("/api/manage/category/add", {name})
    },
    async delCategory(id) {
      await axios.post("/api/manage/category/del", {id})
    },
    async editCategory(id, nName) {
      await axios.post("/api/manage/category/edit", {
        id,
        name: nName
      })
    },
    handleSelection(val) {
      this.selected = val
    }
  },
  computed: {
    onlyOneSelected() {
      return this.selected.length === 1;
    },
    noOneSelected() {
      return this.selected.length === 0;
    }
  },
  beforeMount() {
    this.fetchCategories();
  }
}
</script>

<style scoped>

</style>